﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using timetabling.core;
using System.Data.SqlClient;
using System.Reflection;
using System.Data;

namespace timetabling.dal
{
    public class GenericDAO<T>: IGenericDAO<T>
    {
        private string connectionString;

        private string entityName;

        private IList<string> fieldNames = new List<string>();

        public GenericDAO(string connectionString)
        {
            this.connectionString = connectionString;

            entityName = typeof(T).Name;

            // Esto es similar a la siguiente linea de codigo: fieldNames...
            /*PropertyInfo[] propertyList = typeof(T).GetProperties();

            foreach(var info in propertyList){
                fieldNames.Add(info.Name);
            }*/

            // Landa 
            fieldNames = typeof(T).GetProperties()
                        .Where(p=>string.Compare(p.PropertyType.Namespace, "system", true) == 0)
                        .Select(p => p.Name).ToList();
            }



        public void Add(T entity)
        {
            string.Join(",",fieldNames);

            string command =string.Format("Insert {0} into {1} Values({@2})", 
                                string.Join(",",fieldNames),
                                entityName, 
                                string.Join(",@",fieldNames));
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                SqlCommand sqlCommand = new SqlCommand(command, sqlConnection);

                foreach(var field in fieldNames){
                    sqlCommand.Parameters.AddWithValue(
                            string.Format("@{0}", field), 
                            typeof(T).GetType().GetProperty(field).GetValue(entity,null)
                    ); 
                }


                try
                {
                    sqlConnection.Open();
                    sqlCommand.ExecuteNonQuery();
                }
                finally
                {
                    if (sqlConnection.State != ConnectionState.Closed)
                    {
                        sqlConnection.Close();
                    }
                }
            }
        }
        //}

        public void Update(T entity)
        {
            throw new NotImplementedException();
        }

        public T Get(Guid id)
        {
            throw new NotImplementedException();
        }

        public IList<T> GetAll()
        {
            throw new NotImplementedException();
        }

        public int count()
        {
            throw new NotImplementedException();
        }

        public void Remove(T entity)
        {
            throw new NotImplementedException();
        }
    }
}
